package com.leadership.api.handler.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.leadership.api.handler.UMUHandler;
import com.leadership.api.rao.UMURao;
import com.leadership.entity.LearningMapStudent;
import com.leadership.entity.umu.UMUCourseStat;
import com.leadership.entity.umu.UMUElementStudent;
import com.leadership.entity.umu.UMUExamData;

/**
 * @author haiyan_xiao
 *
 */
@Component("umuHandler")
public class UMUHandlerImpl implements UMUHandler {

    private static final Logger logger = LoggerFactory.getLogger(UMUHandlerImpl.class);

    @Value("#{umu['umu.host']}")
    private String umuHost;
    
    @Value("#{umu['umu.eid']}")
    private String eid;
    
    @Value("#{umu['umu.privateKey']}")
    private String privateKey;
    
    @Value("#{umu['umu.examData.url']}")
    private String examDataUrl;
    
    @Value("#{umu['umu.studentList.url']}")
    private String studentListUrl;
    
    @Value("#{umu['umu.coursestat.url']}")
    private String coursestatUrl;

    @Rao
    private UMURao umuRao;
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.handler.UMUHandler#generateUrl()
     */
    public String generateUrl() {
        long timestamp = new Date().getTime()/1000;
        String token = this.generateToken(timestamp);
        return "timestamp="+timestamp+"&eid=739&token="+token;
    }

    /*
     * (non-Javadoc)
     * @see com.leadership.scheduler.handler.UMUHandler#listExamData(java.lang.String)
     */
    public List<UMUExamData> listExamData(String elementId) {
        try {
            long timestamp = new Date().getTime()/1000;
            String token = this.generateToken(timestamp);
            
            String authorization = this.generateAuthorization();
            String url = umuHost + examDataUrl + "?timestamp=" + timestamp + "&eid=" + eid + "&token=" + token + "&element_id=" + elementId + "&page=1&size=100000";
            
            HttpResult httpResult = umuRao.umuGet(url, authorization);
            
            if(!httpResult.isValid()) {
                logger.error("request exam datas occurs errror, because response is not valid");
                throw BusinessException.newInstance("500", "请求失败");
            } else {
                Map<String, Object> response = JsonUtils.parse(httpResult.getResponseText());
                
                if(Integer.parseInt(response.get("err_code").toString()) != 0) {
                    String errMsg = response.get("err_msg").toString();
                    logger.error("request exam datas occurs errror with response: " + errMsg);
                    throw BusinessException.newInstance(response.get("err_code").toString(), errMsg);
                } else {
                    String responseData = JsonUtils.toJson(response.get("data"));
                    Map<String, Object> responseDataMap = JsonUtils.parse(responseData);
                    
                    String responseList = JsonUtils.toJson(responseDataMap.get("list"));
                    List<UMUExamData> umuExamDatas = JsonUtils.parseAsList(responseList, UMUExamData.class);
                    
                    return umuExamDatas;
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("basic auth occurs error:", e);
            e.printStackTrace();
            throw BusinessException.newInstance("500", "加密异常");
        } catch (Exception e) {
            logger.error("request exam datas occurs error:", e);
            throw BusinessException.newInstance("500", "请求失败");
        }
    }
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.handler.UMUHandler#listUMUElementStudent(java.lang.String)
     */
    public List<UMUElementStudent> listUMUElementStudent(String url) {
        try {
            long timestamp = new Date().getTime()/1000;
            String token = this.generateToken(timestamp);
            url = URLEncoder.encode(url, java.nio.charset.StandardCharsets.UTF_8.toString());
            String authorization = this.generateAuthorization();
            String apiurl = umuHost + studentListUrl + "?timestamp=" + timestamp + "&eid=" + eid + "&token=" + token + "&element_url=" + url + "&page=1&size=100000";
            logger.info("apiurl is [{}]", apiurl);
            logger.info("authorization is [{}]", authorization);
            HttpResult httpResult = umuRao.umuGet(apiurl, authorization);
            
            if(!httpResult.isValid()) {
                logger.error("request exam datas occurs errror, because response is not valid");
                throw BusinessException.newInstance("500", "请求失败");
            } else {
//                logger.info("http result is [{}]", httpResult.getResponseText());
                Map<String, Object> response = JsonUtils.parse(httpResult.getResponseText());
                if(Integer.parseInt(response.get("err_code").toString()) != 0) {
                    String errMsg = response.get("err_msg").toString();
                    logger.error("request exam datas occurs errror with response: " + errMsg);
                    throw BusinessException.newInstance(response.get("err_code").toString(), errMsg);
                } else {
                    
                    String responseData = JsonUtils.toJson(response.get("data"));
                    Map<String, Object> responseDataMap = JsonUtils.parse(responseData);
                    
                    String responseList = JsonUtils.toJson(responseDataMap.get("list"));
                    List<UMUElementStudent> umuExamDatas = JsonUtils.parseAsList(responseList, UMUElementStudent.class);
                    return umuExamDatas;
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("basic auth occurs error:", e);
            e.printStackTrace();
            throw BusinessException.newInstance("500", "加密异常");
        } catch (Exception e) {
            logger.error("request exam datas occurs error:", e);
            throw BusinessException.newInstance("500", "请求失败");
        }
    }
    
    /*
     * (non-Javadoc)
     * @see com.leadership.api.handler.UMUHandler#listUMUElementStudent(com.leadership.entity.LearningMapStudent)
     */
    public UMUCourseStat courseStat(LearningMapStudent learningMapStudent) {
        
        try {
            
            long timestamp = new Date().getTime()/1000;
            String token = this.generateToken(timestamp);
            String url = URLEncoder.encode(learningMapStudent.getLearningMap().getLink(), java.nio.charset.StandardCharsets.UTF_8.toString());
            String authorization = this.generateAuthorization();
            String apiurl = umuHost + coursestatUrl + "?timestamp=" + timestamp + "&eid=" + eid + "&token=" + token + "&program_url=" + url + "&account=" + learningMapStudent.getEmail();
            logger.info("apiurl is [{}]", apiurl);
            logger.info("authorization is [{}]", authorization);
            HttpResult httpResult = umuRao.umuGet(apiurl, authorization);
            
            if(!httpResult.isValid()) {
                logger.error("request exam datas occurs errror, because response is not valid");
                throw BusinessException.newInstance("500", "请求失败");
            } else {
//                logger.info("http result is [{}]", httpResult.getResponseText());
                Map<String, Object> response = JsonUtils.parse(httpResult.getResponseText());
                if(Integer.parseInt(response.get("err_code").toString()) != 0) {
                    String errMsg = response.get("err_msg").toString();
                    logger.error("request exam datas occurs errror with response: " + errMsg);
                    //throw BusinessException.newInstance(response.get("err_code").toString(), errMsg);
                    return null;
                } else {
                    
                    String responseData = JsonUtils.toJson(response.get("data"));
                    UMUCourseStat stat = JsonUtils.parse(responseData, UMUCourseStat.class);
                    return stat;
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("basic auth occurs error:", e);
            e.printStackTrace();
            throw BusinessException.newInstance("500", "加密异常");
        } catch (Exception e) {
            logger.error("request exam datas occurs error:", e);
            throw BusinessException.newInstance("500", "请求失败");
        }
    }

    /**
     * 
     * @return
     * @throws UnsupportedEncodingException
     */
    private String generateAuthorization() throws UnsupportedEncodingException {
        return new String(Base64.encodeBase64((eid + ":" + privateKey).getBytes("utf-8")));
    }

    /**
     * 
     * @param timestamp
     * @return
     */
    private String generateToken(long timestamp) {
        return DigestUtils.md5Hex(String.valueOf(timestamp) + eid + privateKey).substring(4,24);
    }

}
